import { h } from 'vue';

import { setupVbenVxeTable, useVbenVxeGrid } from '@vben/plugins/vxe-table';

import { Avatar, Button, Image, Space, Switch, Tag } from 'ant-design-vue';

import { $t } from '#/locales';

import { useVbenForm } from './form';

setupVbenVxeTable({
  configVxeTable: (vxeUI) => {
    vxeUI.setConfig({
      grid: {
        align: 'center',
        border: false,
        columnConfig: {
          resizable: true,
        },
        minHeight: 180,
        formConfig: {
          // 全局禁用vxe-table的表单配置，使用formOptions
          enabled: false,
        },
        proxyConfig: {
          autoLoad: true,
          response: {
            result: 'records',
            total: 'total',
            list: 'records',
          },
          showActiveMsg: true,
          showResponseMsg: false,
        },
        round: true,
        showOverflow: true,
        size: 'small',
      },
    });

    // 表格配置项可以用 cellRender: { name: 'CellImage' },
    vxeUI.renderer.add('CellImage', {
      renderTableDefault(_renderOpts, params) {
        const { column, row } = params;
        return h(Image, { src: row[column.field] });
      },
    });

    // 表格配置项可以用 cellRender: { name: 'CellAvatar' },
    vxeUI.renderer.add('CellAvatar', {
      renderTableDefault(_renderOpts, params) {
        const { column, row } = params;
        return h(Avatar, { src: row[column.field] });
      },
    });

    // 表格配置项可以用 cellRender: { name: 'CellLink' },
    vxeUI.renderer.add('CellLink', {
      renderTableDefault(renderOpts) {
        const { props } = renderOpts;
        return h(
          Button,
          { size: 'small', type: 'link' },
          { default: () => props?.text },
        );
      },
    });

    // 操作列渲染器
    vxeUI.renderer.add('CellOperation', {
      renderTableDefault(renderOpts, params) {
        const { row } = params;
        const { attrs } = renderOpts;
        const { actions = [], onClick } = attrs || {};

        return h(
          Space,
          {},
          {
            default: () =>
              actions.map((action: { code: string; name: string }) => {
                return h(
                  Button,
                  {
                    type: 'link',
                    size: 'small',
                    danger: action.code === 'delete',
                    onClick: () => {
                      if (onClick) {
                        onClick({ code: action.code, row });
                      }
                    },
                  },
                  { default: () => action.name },
                );
              }),
          },
        );
      },
    });

    // 状态开关渲染器
    vxeUI.renderer.add('CellSwitch', {
      renderTableDefault({ attrs, props }, { column, row }) {
        const loadingKey = `__loading_${column.field}`;
        const finallyProps = {
          checkedChildren: $t('common.enabled'),
          checkedValue: 1,
          unCheckedChildren: $t('common.disabled'),
          unCheckedValue: 0,
          ...props,
          checked: row[column.field],
          loading: row[loadingKey] ?? false,
          'onUpdate:checked': onChange,
        };
        async function onChange(newVal: any) {
          row[loadingKey] = true;
          try {
            const result = await attrs?.beforeChange?.(newVal, row);
            if (result !== false) {
              row[column.field] = newVal;
            }
          } finally {
            row[loadingKey] = false;
          }
        }
        return h(Switch, finallyProps);
      },
    });

    // 状态标签渲染器
    vxeUI.renderer.add('CellTag', {
      renderTableDefault({ attrs = {}, props: _props }, { column, row }) {
        const value = row[column.field];
        let label;
        let color;

        // 1. 支持 map: { value: { label, color } } 或 { value: label }
        if (attrs.map) {
          const _map = attrs.map as Record<
            number | string,
            string | { color?: string; label: string }
          >;
          const mapItem = _map[value];
          if (typeof mapItem === 'object' && mapItem !== null) {
            label = mapItem.label;
            color = mapItem.color;
          } else if (typeof mapItem === 'string') {
            label = mapItem;
          }
        }

        // 2. 支持 colorMap: { value: color }
        if (!color && attrs.colorMap) {
          const _colorMap = attrs.colorMap as Record<number | string, string>;
          color = _colorMap[value];
        }

        // 3. 默认颜色
        if (!color && attrs.defaultColor) {
          const _defaultColor = attrs.defaultColor;
          color = _defaultColor;
        }

        // 4. 默认状态
        if (!label) {
          const statusMap: Record<number, { color: string; label: string }> = {
            0: { color: 'red', label: $t('common.disabled') },
            1: { color: 'green', label: $t('common.enabled') },
          };
          const tagItem = statusMap[value] || {
            color: 'default',
            label: String(value),
          };
          label = tagItem.label;
          color = color || tagItem.color;
        }

        // 5. 允许透传attrs给Tag（如size、style等，但排除map/colorMap/defaultColor）
        const {
          /* eslint-disable @typescript-eslint/no-unused-vars */ map,
          colorMap,
          defaultColor,
          /* eslint-enable @typescript-eslint/no-unused-vars */
          ...tagAttrs
        } = attrs;

        return h(
          Tag,
          {
            color,
            ...tagAttrs,
          },
          { default: () => label },
        );
      },
    });

    // 这里可以自行扩展 vxe-table 的全局配置，比如自定义格式化
    // vxeUI.formats.add
  },
  useVbenForm,
});

export { useVbenVxeGrid };

export type * from '@vben/plugins/vxe-table';
